/*
 * Created on 2004-12-30
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
package com.tss.util;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Properties;

/**
 * @author Administrator
 *
 * TODO To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
public class DbKeyGen {
	private static DbKeyGen keygen = null;
	private static Object initLock = new Object();
	public static long nextID(String type) {
		if (keygen == null) {
			synchronized(initLock) {
				if (keygen == null) {
					keygen = new DbKeyGen();
				}
			}
		}
		return keygen.nextUniqueID(type.trim().toUpperCase());
	}
	
	private HashMap uniqueIDCounters;

	public DbKeyGen() {
		uniqueIDCounters = new HashMap();
		Properties properties = new Properties();
		InputStream in = null;
		try {
			in = getClass().getResourceAsStream("/keygen.properties");
			properties.load(in);
			Enumeration objEnum = properties.propertyNames();
			
			while (objEnum.hasMoreElements()){
				String keyName = objEnum.nextElement().toString();
				String keySql = properties.getProperty(keyName);
				uniqueIDCounters.put(keyName.trim().toUpperCase(), new Counter(getNextDbID(keySql)));
			}
		}
		catch (Exception e) {
			System.err.println("Error reading conf properties in PropertyManager.loadProps() " + e);
			e.printStackTrace();
		}
		finally {
			try {
				in.close();
			} catch (Exception e) { }
		}
	}

	public long nextUniqueID(String counterName) {
		Counter counter = (Counter)uniqueIDCounters.get(counterName);
		if (counter==null) return -1;
		return counter.next();
	}

	private long getNextDbID(String query) {
		long currentID = 0;
		Connection con = null;
		PreparedStatement pstmt = null;
		try {
			con = DbConnectionManager.getConnection();
			pstmt = con.prepareStatement(query);
			ResultSet rs = pstmt.executeQuery();
			rs.next();
			currentID = rs.getInt(1);
		}
		catch( Exception sqle ) {
			System.err.println("Error in DbSequenceManager:getNextDbID()-" + sqle);
			sqle.printStackTrace();
		}
		finally {
			try {  pstmt.close(); }
			catch (Exception e) { e.printStackTrace(); }
			try {  con.close();   }
			catch (Exception e) { e.printStackTrace(); }
		}
		//If the table is empty, start with id 0
		if (currentID < 0) {
			currentID = 0;
		}
		return currentID;
	}

	private final class Counter {
		private long count;
		public Counter(long currentCount) {
			count = currentCount;
		}
		public final synchronized long next() {
			return (++count);
		}
	}
}
